package com.ktg.mes.chanjet.controller;


import cn.hutool.json.JSONObject;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.chanjet.response.GetVoucherResponse;
import com.ktg.mes.chanjet.spi.ChanjetSpi;
import com.ktg.mes.chanjet.vo.QueryOrderVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/purOrder")
public class PurOrderController {

    @Autowired
    private ChanjetSpi chanjetSpi;


    @PostMapping("/list")
    public Result<Object> findPurOrderList(@RequestBody QueryOrderVo vo) throws ChanjetApiException {
        GetVoucherResponse getVoucherResponse = chanjetSpi.getPurchaseOrderList(vo);
        Map<String, Object> data = getVoucherResponse.getData();
        converData(data);
        return Result.OK(data);
    }


    @GetMapping("/getOrder")
    @ApiOperation("查询销售订单")
    public Result<Object> GetVoucher(@RequestParam("code")String code) throws ChanjetApiException {
        return Result.OK(chanjetSpi.getPurchaseOrder(code).getData());
    }

    private Map<String,Object> converData(Map<String,Object> map){
        List<String> columns = (List<String>) map.get("Columns");
        List<List> rows = (List<List>) map.get("Rows");
        List<JSONObject> list = new ArrayList<>();
        for (List row: rows) {
            JSONObject jsonRow = new JSONObject();
            for (int i = 0; i < row.size(); i++) {
                jsonRow.putOpt(columns.get(i),row.get(i));
            }
            list.add(jsonRow);
        }
        map.put("records",list);
        return map;
    }
}
